#!/usr/bin/env python
# coding: utf-8
import web
from config import settings
from config import util
import datetime,json
from datetime import timedelta
import authbase

render = settings.render
db = settings.db

class SelectedHourChart(authbase.AuthBase):
    def GET(self):
        stations_input = web.input(stations=[])
        #print "stations_input:%s"%stations_input
        stations = stations_input.get('stations',None)
        where_str=" 1=1 "
        if stations:
            where_str=where_str+" and site in ('"+"','".join(stations)+"')"
            selected_stations=stations
        else:
            selected_stations=[]

        data_type_input = web.input(data_type=[])
        #print "data_type_input:%s"%data_type_input
        data_type_names = data_type_input.get('data_type',None)
        #print "data_types:%s"%data_type_names

        i = web.input()
        #print i
        #显示自动计算平均值和最大最小值
        reference_compute_avg=i.get('reference_compute_avg', False)
        selected_hour = i.get('select_hour', '00')
        where_str=where_str+" and collection_hour = '"+selected_hour+"'"

        start_date = i.get('dateStart', None)
        #默认最近一个月#上月1号
        if start_date is None:
            last_month_start=datetime.date(datetime.date.today().year,datetime.date.today().month-1,1)
            start_date= datetime.datetime.strftime(last_month_start, "%Y-%m-%d")
        where_str=where_str+" and collection_date >= '"+start_date+"'"
        selected_start_date=start_date

        end_date = i.get('dateEnd', None)
        if end_date is None:
            end_date=datetime.datetime.strftime(datetime.date.today(), "%Y-%m-%d")
        #必须先排好顺序
        where_str=where_str+" and collection_date <= '"+end_date+"' order by site,collection_date"
        selected_end_date=end_date

        #将查询结果转为list，可以多次遍历
        data_list =list(db.query("SELECT * FROM site_hour_data where "+where_str))
        stations=list(db.select('stations'))
        #根据监测站和指标类型的不同组合来生成曲线数据
        line_name_dict,chart_data_array=self.create_chart_data(selected_stations,data_type_names,data_list,selected_start_date,selected_end_date)
        #print line_name_dict,chart_data_array
        return render.type_charts.selected_hour_chart(data_list=data_list,chart_data_array=util.two_array_to_utf_string(chart_data_array),line_name_dict=line_name_dict, stations=stations,\
                                      selected_stations=selected_stations,selected_start_date=selected_start_date,
                                      selected_end_date=selected_end_date,data_type_names=data_type_names,\
                                      data_type_titles=util.create_field_title_by_avg_name(data_type_names),reference_compute_avg=reference_compute_avg,selected_hour=selected_hour)

    def create_chart_data(self,selected_stations,data_type_names,data_list,selected_start_date,selected_end_date):
        #按监测站、参数类型的组合方式来生成曲线
        data_array=[]
        line_dict={}
        i=0
        #生成X坐标轴：日期（00）,必须要考虑日期缺漏的情况，不同监测站的日期不一致怎么办
        x_array=util.create_date_array(selected_start_date,selected_end_date)
        x_array.insert(0,"x_time_array")
        line_dict["line00"]="x_time_array"
        data_array.append(x_array)

        if selected_stations is None:
            return line_dict,data_array
        for station in selected_stations:
            #先判断数据集里面是否有该监测站
            station_exist=util.is_station_in_data_list(station,data_list)
            if station_exist==False:
                print "%s not in satations"%station
                continue
            short_name=station[0:2]
            for data_type in data_type_names:
                title=short_name+util.data_type_title_dict[data_type]
                row_array=[]
                begin = datetime.datetime.strptime(selected_start_date, "%Y-%m-%d")
                end = datetime.datetime.strptime(selected_end_date, "%Y-%m-%d")
                #生成某站点 在指定的日期范围内 某种监测类型的数据array
                for index in range((end - begin).days+1):
                    day = begin + timedelta(days=index)
                    #print day.strftime("%Y-%m-%d")
                    #在data_list中查找监测站名称、日期符合的记录，找到后返回指定数据列的值,没找到返回‘’
                    result_value=util.query_site_date_type_value(station,day.strftime("%Y-%m-%d"),data_type,data_list)
                    row_array.append(result_value)

                #如果全部都是‘’空值，说明没有这个监测站的数据
                if len(row_array)==0:
                    print "%s row_array is null.query_site_date_type_value(%s,%s,%s)"%(title,station,day.strftime("%Y-%m-%d"),data_type)
                    continue
                #曲线编号和中文名称对应
                line_dict[data_type+"_%02d"%i]=title
                row_array.insert(0,title)
                data_array.append(row_array)

                i=i+1
        return line_dict,data_array




class DateRangeChart(authbase.AuthBase):
    def GET(self):
        stations_input = web.input(stations=[])
        #print "stations_input:%s"%stations_input
        stations = stations_input.get('stations',None)
        where_str=" 1=1 "
        if stations:
            where_str=where_str+" and site in ('"+"','".join(stations)+"')"
            selected_stations=stations
        else:
            selected_stations=[]

        data_type_input = web.input(data_type=[])
        #print "data_type_input:%s"%data_type_input
        data_type_names = data_type_input.get('data_type',None)
        #print "data_types:%s"%data_type_names

        i = web.input()
        print i
        #显示自动计算平均值和最大最小值
        reference_compute_avg=i.get('reference_compute_avg', False)

        start_date = i.get('dateStart', None)
        #默认最近一个月#上月1号
        if start_date is None:
            last_month_start=datetime.date(datetime.date.today().year,datetime.date.today().month-1,1)
            start_date= datetime.datetime.strftime(last_month_start, "%Y-%m-%d")
        where_str=where_str+" and collection_date >= '"+start_date+"'"
        selected_start_date=start_date

        end_date = i.get('dateEnd', None)
        if end_date is None:
            end_date=datetime.datetime.strftime(datetime.date.today(), "%Y-%m-%d")
        #必须先排好顺序
        where_str=where_str+" and collection_date <= '"+end_date+"' order by site,collection_date,collection_hour"
        selected_end_date=end_date

        #将查询结果转为list，可以多次遍历
        data_list =list(db.query("SELECT * FROM site_hour_data where "+where_str))
        stations=list(db.select('stations'))
        #根据监测站和指标类型的不同组合来生成曲线数据
        line_name_dict,chart_data_array=self.create_chart_data(selected_stations,data_type_names,data_list,selected_start_date,selected_end_date)
        #print chart_data_array
        return render.type_charts.date_range_chart(data_list=data_list,chart_data_array=util.two_array_to_utf_string(chart_data_array),line_name_dict=line_name_dict, stations=stations,\
                                      selected_stations=selected_stations,selected_start_date=selected_start_date,
                                      selected_end_date=selected_end_date,data_type_names=data_type_names,\
                                      data_type_titles=util.create_field_title_by_avg_name(data_type_names),reference_compute_avg=reference_compute_avg)

    def create_chart_data(self,selected_stations,data_type_names,data_list,selected_start_date,selected_end_date):
        #按监测站、参数类型的组合方式来生成曲线
        data_array=[]
        line_dict={}
        i=0
        #生成X坐标轴：日期+时段（00-23）
        x_array=util.create_date_24hour_array(selected_start_date,selected_end_date)
        x_array.insert(0,"x_time_array")
        line_dict["line00"]="x_time_array"
        data_array.append(x_array)

        if selected_stations is None:
            return line_dict,data_array
        for station in selected_stations:
            short_name=station[0:2]
            for data_type in data_type_names:
                title=short_name+util.data_type_title_dict[data_type]
                #生成数据
                row_array=[]
                for data in data_list:
                    if data.site==station:
                        row_array.append(str(data[data_type]))
                if len(row_array)==0:
                    continue
                #曲线编号和中文名称对应
                line_dict[data_type+"_%02d"%i]=title
                row_array.insert(0,title)
                data_array.append(row_array)
                i=i+1
        return line_dict,data_array
